package com.sina.finance.api.framework.permission.init.impl;

import com.sina.finance.api.framework.permission.init.PrivilegeInitTool;
import com.sina.finance.api.framework.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @File name : impl
 * @Description :
 * @Creator : cuiyong
 * @CreateTime : 15/11/11 16:39
 * @Version : 1.0
 * @Update records:
 * 1.0 15/11/11 by cuiyong: Created
 * All rights served : SINA Corporation
 */
public class PrivilegeInitToolImpl implements PrivilegeInitTool{

    private PerminssionService perminssionService;

    public void init() {
        this.initPrivilege();
        this.initDefaultRole();
        this.initDefaultSubject();
    }

    protected void initDefaultRole() {
        Set<SysPrivilege> allPrivilegesInRep = perminssionService.getAllPrivilegesInRep();

        SysRole sysRole = configDefaultRole(allPrivilegesInRep);

        List<Long> privilegesPersistencedKeys = new ArrayList<Long>();
        for (SysPrivilege sysPrivilege : allPrivilegesInRep) {
            privilegesPersistencedKeys.add(sysPrivilege.getId());
        }
    }

    protected void initDefaultSubject() {

    }

    protected void initPrivilege() {


        Set<SysPrivilege> allPrivilegesInRep = perminssionService.getAllPrivilegesInRep();

        Set<SysPrivilege> allPrivilegesInProject = perminssionService.getAllPrivilegesInProject();

        Set<SysPrivilege> toDelete = CollectionUtils.complement(allPrivilegesInRep, allPrivilegesInProject);
        Set<SysPrivilege> toInsert = CollectionUtils.complement(allPrivilegesInProject, allPrivilegesInRep);

        perminssionService.savePrivilege(toInsert);
        perminssionService.removePrivilege(toDelete);
    }


    private SysRole configDefaultRole(Set<SysPrivilege> allPrivilegesInRep) {


        SysRole sysRole = perminssionService.getDefaultRole();
        if(sysRole == null) {
            sysRole = sysRole.createDefaultRole();
            perminssionService.resetPrivilegeOfDefaultRole(allPrivilegesInRep, sysRole);
            perminssionService.saveRole(sysRole);
        } else {
            perminssionService.resetPrivilegeOfDefaultRole(allPrivilegesInRep, sysRole);
            perminssionService.updateRole(SysRole.class, sysRole);
        }

        return sysRole;
    }
}
